// pages/mine/mine.js
const db = wx.cloud.database()
const app = getApp()
import Toast from '../../vant/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: {
      title: ''
    },
    headImgUrl: '',
    nickName: '',
    tab: {
      list: [{
        title: '待发货',
        cards: []
      }, {
        title: '已发货',
        cards: []
      }, {
        title: '已收货',
        cards: []
      }],
      activeTab: 0,
      width: 50,
      color: '#333',
      btnDisabled: false
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },
  onShow() {
    this.getOrderData()
    // 获取用户缓存的头像信息
    try {
      let headImgUrl = wx.getStorageSync('headImgUrl')
      let nickName = wx.getStorageSync('nickName')
      if (headImgUrl || nickName) {
        // Do something with return value
        this.setData({
          headImgUrl: headImgUrl,
          nickName: nickName,
          btnDisabled: true
        })
      }
    } catch (e) {
      // Do something when catch error
    }
    // 获取用户缓存的头像信息 ---over
  },
  onGotUserInfo(e) {
    this.setData({
      headImgUrl: e.detail.userInfo.avatarUrl,
      nickName: e.detail.userInfo.nickName
    })
    try {
      wx.setStorageSync('headImgUrl', e.detail.userInfo.avatarUrl)
      wx.setStorageSync('nickName', e.detail.userInfo.nickName)
    } catch (e) {
      console.log(e)
    }

    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        app.globalData.openid = res.result.openid
        wx.setStorageSync('openId', res.result.openid)

        this.setData({
          btnDisabled: true
        })

        // 获取用户信息后 查询数据
        this.getOrderData()

        // 将用户信息存入user_list中
        // wx.cloud.callFunction({
        //   name: 'addList',
        //   data: {
        //     listName: 'user_list',
        //     form: {
        //       _openid: res.result.openid,
        //       headImgUrl: e.detail.userInfo.avatarUrl,
        //       nickName: e.detail.userInfo.nickName,
        //       city: e.detail.userInfo.city,
        //       country: e.detail.userInfo.country,
        //       gender: e.detail.userInfo.gender,
        //       language: e.detail.userInfo.language,
        //       province: e.detail.userInfo.province
        //     }
        //   },
        //   success: res => {
        //     console.log(res.result)
        //     this.setData({
        //       btnDisabled: true
        //     })
        //   },
        //   fail: err => {
        //     console.err('登录失败')
        //   }
        // })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  handleChange ({ detail }) {
    this.setData({
      current: detail.key
    });
  },
  onTabChange() {
    // tab切换事件
  },
  getOrderData() {
    const $this = this
    let openId = app.globalData.openid
    // 获取各个订单数据
    db.collection('order_list').where({
      _openid: openId, // 填入当前用户 openid
      enable: 1
    }).get({
      success: function(res) {
        let orderData = res.data
        // 初始化数据
        $this.data.tab.list[0].cards = []
        $this.data.tab.list[1].cards = []
        $this.data.tab.list[2].cards = []
        for(let i = 0, len = orderData.length; i < len; i ++) {
          let status = orderData[i].status
          switch(status) {
            case 0:
              // 待发货
              $this.data.tab.list[0].cards.push(orderData[i])
            break;
            case 1:
              // 已发货
              $this.data.tab.list[1].cards.push(orderData[i])
            break;
            case 2:
              // 已收货
              $this.data.tab.list[2].cards.push(orderData[i])
            break;
          }
        }
        $this.setData({
          'tab.list': $this.data.tab.list
        })
      }
    })
  },
  jumpToOrder(e) {
    let list = this.data.tab.list
    let { tabindex, dataindex } = e.target.dataset
    // 选中的订单详情
    let {goodList, addressInfo} = list[tabindex].cards[dataindex]
    let goodListStr = JSON.stringify(goodList)
    let addressInfoStr = JSON.stringify(addressInfo)
    // 获取订单总共价格
    let priceSum = 0
    for(let i = 0, len = goodList.length; i < len; i ++) {
      let thisGood = goodList[i]
      priceSum += thisGood.count * thisGood.goodDetail.price * 100
    }
    wx.navigateTo({
      url: `/pages/order/order?listData=${goodListStr}&priceSum=${priceSum}&isPay=${true}&addressInfo=${addressInfoStr}`
    })
  },
})